package com.hsir.fileUpload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private List<File> file;
    public List<File> getFile() {
		return file;
	}

	public void setFile(List<File> file) {
		this.file = file;
	}

	private List<String> fileFileName;
    private List<String> fileContentType;
    
    public String execute() throws IOException{
    //得到工程保存图片的路径
//      String root = ServletActionContext.getRequest().getRealPath("/upload");
    	String root= ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/upload");
    	file = this.getFile();
        if(null != file){
        	//循环上传的文件
        	for(int i = 0 ; i < file.size() ; i ++){
        		InputStream is = new FileInputStream(file.get(i));
        		
        		//得到图片保存的位置(根据root来得到图片保存的路径在tomcat下的该工程里)
        		File destFile = new File(root,this.getFileFileName().get(i));
        		
        		//把图片写入到上面设置的路径里
        		OutputStream os = new FileOutputStream(destFile);
        		byte[] buffer = new byte[400];
        		int length  = 0 ;
        		while((length = is.read(buffer))>0){
        			os.write(buffer, 0, length);
        		}
        		is.close();
        		os.close();
        	}
        }
        return SUCCESS;
    }

	public List<String> getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(List<String> fileFileName) {
		this.fileFileName = fileFileName;
	}

	public List<String> getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(List<String> fileContentType) {
		this.fileContentType = fileContentType;
	}
}
